package com.ruoyi.file.service;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.ruoyi.common.core.utils.uuid.UUID;
import com.ruoyi.file.config.AliOSSConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

/**
 * @author 侯文波
 * @date 2025/3/6 10:52
 * @description:
 */
@Primary
@Service
public class AliOSSSysFileServiceImpl implements ISysFileService{

    @Autowired
    private AliOSSConfig aliOSSConfig;


    @Override
    public String uploadFile(MultipartFile file) throws Exception {
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(aliOSSConfig.getEndPoint(), aliOSSConfig.getAccessKeyId(), aliOSSConfig.getSecretAccessKey());

        //获得当前时间
        LocalDate today = LocalDate.now();

        // 定义日期格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");

        // 将当前日期格式化为字符串//设置文件名
        String fileName = today.format(formatter)
                + UUID.randomUUID().toString().replace("-", "")
                + file.getOriginalFilename();

        try {
            // 创建PutObject请求。
            ossClient.putObject(aliOSSConfig.getBucketName(), fileName, file.getInputStream());
            String url = "https://" + aliOSSConfig.getBucketName() + "." + aliOSSConfig.getEndPoint() + "/" + fileName;
            return url;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}
